package goplatform

import (
	"errors"
	"io"
	"log"
)

type PModel struct {
	Name   string `json:"Name" xml:"Name" form:"Name"`
	Fields []PField
}

type PField struct {
	Name     string `json:"Name" xml:"Name" form:"Name"`
	Attr     PAttr
	CType    string `json:"CType" xml:"CType" form:"CType"`
	Elements map[string]interface{}
}

type PAttr struct {
	Primary  bool `json:"primary" xml:"primary" form:"primary"`
	Required bool `json:"Required" xml:"Required" form:"Required"`
	Order    bool `json:"Order" xml:"Order" form:"Order"`
	Unique   bool `json:"Unique" xml:"Unique" form:"Unique"`
}

var (
	templatePath          = "../templates"
	modelTemplateFileName = "model_route_template.tmpl"
	defaultPrimaryField   = PField{
		Name: "ID", CType: "uint",
		Attr: PAttr{Required: true}}
)

type ModelConfig struct {
	Model PModel

	TemplatePath      string
	TemplateModelFile string

	//SuccessHandler fiber.Handler
	//ErrorHandler fiber.ErrorHandler

	// Create Template RunTime Vars
	//Model             *Model
	//Service           *Service
	//PModel            *PModel
	HasPrimary     bool
	PrimaryName    string
	ImportPackages []string
}

func NewModelFactory(config ModelConfig) (*ModelConfig, error) {
	var cfg ModelConfig
	if config.Model.Name == "" {
		return &cfg, errors.New("Model Name Is Empty. ")
	}
	cfg.Model = config.Model
	if config.TemplatePath == "" {
		cfg.TemplatePath = templatePath
	}
	if config.TemplateModelFile == "" {
		cfg.TemplateModelFile = modelTemplateFileName
	}

	// Check
	ff, _ := GetFieldFactory()
	for _, field := range cfg.Model.Fields {
		if field.Elements["primary"] == "true" {
			cfg.PrimaryName = field.Name
			cfg.HasPrimary = true
		}
		// Add Other Import Package
		fCType := field.CType
		switch fCType {
		case "time":
			//fCType = "time.Time"
			cfg.ImportPackages = append(cfg.ImportPackages, "time")
		case "string":
		default:

		}

		//
		if _, err := ff.GetFieldType(fCType); err != nil {
			log.Printf("\n ----> GetFieldType %+v\n", err)
		}

	}
	// Add Pre PrimaryID
	if !cfg.HasPrimary {
		cfg.ImportPackages = append(cfg.ImportPackages, "gorm.io/gorm")
		cfg.PrimaryName = "ID"
		// ADD Primary
		cfg.Model.Fields = append(cfg.Model.Fields, defaultPrimaryField)
	}

	return &cfg, nil
}

func (mc *ModelConfig) FieldsIsValid() error {

	return nil
}

func (mc *ModelConfig) IsValid() error {

	return nil
}

func (mc *ModelConfig) Write(writer io.Writer) error {
	return nil
}
